import router from './index'
import { useRouterStore } from '../store/route'
import { cloneDeep } from 'lodash'

// 从菜单里面找到第一个页面
export const getFirstPage = (routes) => {
  for (const route of routes) {
    if (route.menuType === 'menu') {
      return route.path
    } else {
      return getFirstPage(route.children || [])
    }
  }
}
const formatRouter = (routerList) => {
  return routerList.map((item) => {
    if (Array.isArray(item.children)) {
      item.children = formatRouter(item.children || [])
    }
    let rootModules = import.meta.glob('../views/**/*.vue')
    let projectModules = import.meta.glob('../projects/**/*.vue')
    let compModules = import.meta.glob('../components/**/*.vue')
    item.meta.id = item.id

    if (item.menuType === 'menu') {
      if (item.component.slice(0, 6) === '/views') {
        item.component = rootModules['..' + item.component]
      } else {
        if (item.component.endsWith('index')) {
          item.component = rootModules['../views' + item.component + '.vue']
        } else if (item.component.endsWith('.vue')) {
          item.component = rootModules['../views' + item.component]
        } else {
          item.component = rootModules['../views' + item.component + '/index.vue']
        }
      }
    } else if (item.menuType === 'folder') {
      item.component = compModules[item.component]
    }
    return item
  })
}

// 新增动态路由
export const addTrendsRouteList = async () => {
  const { routes } = storeToRefs(useRouterStore())
  const { getRouter } = useRouterStore()
  let resMenu = []
  // 判断是直接从缓存获取还是接口获取
  if (routes.value.length > 0) {
    resMenu = routes.value
  } else {
    resMenu = await getRouter()
  }
  router.addRoute({
    path: '/',
    component: () => import('@/components/Layout/index.vue'),
    name: 'layout',
    children: formatRouter(cloneDeep(resMenu)),
  })
}
